<template>
    <div class="balanceReport">
        <div class="tabHeader">
            <el-tabs v-model="editableTabsValue" @tab-click="handleTabClick">
                <el-tab-pane v-for="(item,index) in editableTabs" :key="item.id" :name="item.name" :label="item.name">
                    <span slot="label">
                        <el-popover placement="bottom-start"
                            popper-class='custom'>
                            <span slot="reference">{{item.name}}</span>
                            <div class="secondGroup">
                                <div class="item-card" v-for="(i,index) in secondGroupInfo.typeCountData" 
                                    :key="i.optionValue" 
                                    :class="{active:activeValue === i.optionValue}"
                                    @click="handleSecondGroup(i,secondGroupInfo,item)">
                                    <i class="iconfont icon-caiyouduo_hemaixiangqing-fanganxiangqing icon" style="font-size:18px"></i>
                                    <span class="groupName">{{i.optionName}}</span>
                                    <span class="groupName" style="margin-left:8px">{{i.optionNum}}</span>
                                </div>
                            </div>
                        </el-popover>
                    </span>
                </el-tab-pane>
            </el-tabs>

            <div class="setBtn">
                <my-button type='primary' plain size='mini' class='el-icon-circle-check'
                    @btnClick='$refs.saveScheme.showDialog()'>
                    保存当前
                </my-button>
                <my-button type='primary' size='mini' class='el-icon-edit-outline'
                    @btnClick='$refs.scheme.drawerOpen()'>
                    筛选方案
                </my-button>
            </div>
        </div>

        <!-- 动态表单 -->
        <dynamic-form :formDataList='formDataList' @getFormData='getFormData' ref='dynamicForm'></dynamic-form>

        <!-- 按钮操作 -->
        <custom-setbtn>
            <template #l_btn>
                <div class="l_btn">
                    <el-button type="primary" size="mini" icon="el-icon-upload2" plain 
                        :disabled='computedTotal' @click='getWorkOrderExport'>导出
                    </el-button>
                </div>
            </template>
            <template #r_btn>
                <div class="r_btn">
                    <!-- 列配置表格 -->
                    <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup'></pop-checkbox>
                </div>
            </template>
        </custom-setbtn>

        <!-- 表格 -->
        <table-list :tableGroup='tableGroup' :searchForm='searchForm' @getTotal='getTotal' 
            @getSecondGroupInfo="getSecondGroupInfo" ref='tableList'>
        </table-list>

        <!-- 保存当前 -->
        <save-current ref="saveScheme" @getList='getList' :editableTabs='allTabs' @fromOutDrawerClose='fromOutDrawerClose'></save-current>

        <!-- 筛选方案--创建方案 -->
        <operate-scheme ref="scheme" :editableTabs='allTabs' @getList='getList' @fromOutDrawerClose='fromOutDrawerClose'
            @lastData='lastData'></operate-scheme>
    </div>
</template>

<script>
    import {
        screenPlanList
    } from '@/api/produceController'
    import {
        productColumns
    } from '@/api/customFieldController'
    import saveCurrent from './saveCurrent.vue'
    import operateScheme from './operateScheme.vue'
    import tableList from './tableList.vue'
    import dynamicForm from '@/components/dynamicForm'
    import commonDialog from './dialog.vue'
    export default {
        data() {
            return {
                editableTabsValue: '',
                editableTabs: [],
                allTabs:[],
                fromSavaCurrent:0,
                isMounted:'',
                secondGroupInfo:[],
                activeValue:'all',
                enumState:{
                    0:'未开始',
                    1:'执行中',
                    2:'已结束',
                    3:'已取消'
                },
                enumDynamicType:{
                    1:'今天',
                    2:'昨天',
                    3:'本周',
                    4:'上周',
                    5:'本月',
                    6:'上月',
                    7:'近三月',
                },
                enumAttribute:{
                    0:'自制',
                    1:'外购',
                    2:'委外'
                },
                enumType:{
                    0:'库存数量 < 安全库存',
                    1:'库存数量 < 最小库存',
                    2:'库存数量 > 最大库存'
                },
                customFieldMap:{},
                isCollapse: false,
                formDataList: {
                    formGroup: [
                        {
                            label: 'productCode',
                            name: '产品编号',
                            placeholder: '请输入产品编号',
                            key: 'srk',
                        },
                        {
                            label: 'productName',
                            name: '产品名称',
                            placeholder: '请输入产品名称',
                            key: 'srk'
                        },
                        {
                            label: 'productSpecification',
                            name: '产品规格',
                            placeholder: '请输入产品规格',
                            key: 'srk'
                        },
                         {
                            label: 'attribute',
                            name: '产品属性',
                            placeholder: '请选择',
                            key: 'sel',
                            node: {
                                default: '',
                                isRadio: true,
                                options: [{
                                        value: 0,
                                        label: '自制'
                                    },
                                    {
                                        value: 1,
                                        label: '外购'
                                    },
                                    {
                                        value: 2,
                                        label: '委外'
                                    }
                                ]
                            }
                        },
                        {
                            label: ['maximumDown', 'maximumUp'],
                            name: '最大库存',
                            key: 'jsk'
                        },
                        {
                            label: ['minimumDown', 'minimumUp'],
                            name: '最小库存',
                            key: 'jsk'
                        },
                        {
                            label: ['safeDown', 'safeUp'],
                            name: '安全库存',
                            key: 'jsk'
                        },
                        {
                            label: 'typeOther',
                            name: '常用筛选',
                            placeholder: '请选择',
                            key: 'sel',
                            node: {
                                default: '',
                                isRadio: true,
                                options: [{
                                        value: 0,
                                        label: '库存数量<安全库存'
                                    },
                                    {
                                        value: 1,
                                        label: '库存数量<最小库存'
                                    },
                                    {
                                        value: 2,
                                        label: '库存数量>最大库存'
                                    }
                                ]
                            }
                        },
                    ],
                    searchForm: {
                        productCode: '',
                        productName: '',
                        productSpecification: '',
                        attribute:'',
                        maximumDown:'',
                        maximumUp:'',
                        minimumDown:'',
                        minimumUp:'',
                        safeDown:'',
                        safeUp:'',
                        typeOther: ''
                    },
                    formSet: true,
                    type:'stockBalance'
                },
                searchForm:{
                    customFieldMap:{},
                    searchOther:{},
                    page:1,
                    limit:10,
                },
                checkList: [],
                drawer: false,
                operateRecordTable: [],
                total: 0,
                tableTotal:0,
                operateParams: {
                    type: 0,
                    page: 1,
                    limit: 8
                },
                disposeGroup: [],
                tableGroup:[],
            }
        },
        components: {
            saveCurrent,
            operateScheme,
            dynamicForm,
            tableList,
            commonDialog
        },
        mounted(){
            this.isMounted = 'mounted'
            this.getProductColumns({
                type: 'stockBalance'
            })
            this.getScreenPlanList({type:2})
        },
        computed:{
            computedTotal(){
                return this.tableTotal <= 0
            }
        },
        watch:{
            tableTotal(total){
                //当表格数据为空时 列配置和表头无自定义字段信息
                if(total <= 0) {
                    this.tableGroup = this.utils.filterCustomFields(this.tableGroup)
                    this.disposeGroup = this.utils.filterCustomFields(this.disposeGroup)
                }
            }
        },
        methods: {
            getProductColumns: async function(data){
                const res = await productColumns(data)
                if (res.code == 200) {
                    this.disposeGroup = []
                    this.tableGroup = []
                    res.data.map((item, i) => {
                        const key = {
                                index:'80',
                                processRouteName:'80',
                                specification:'70',
                                unitName:'70',
                                stock:'80',
                                createTime:'150',
                                createName:'70',
                                updateTime:'150',
                                maximum:'70',
                                minimum:'70',
                                safe:'70',
                                attribute:'80'
                            }
                        let width = key[item.name] ?? '180'
                        if (item.state) {
                            this.tableGroup.push({
                                label: item.name,
                                name: item.chineseName,
                                width
                            })
                        }
                        this.disposeGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            state: item.state
                        })
                    })
                }
            },
            //监视复选框值变化
            handleChangeDiposeGroup(disposeGroup) {
                let configureList = []
                configureList = disposeGroup.map(i => {
                    return {
                        name: i.label,
                        chineseName: i.name,
                        state: i.state
                    }
                })
                this.getProductColumns({
                    type: 'stockBalance',
                    configureList
                }).then(()=>{
                    this.$refs.tableList.updateTable()
                })
            },
            getTotal(total){
                this.tableTotal = total
            },
            //点击查询获取表单数据
            getFormData(val) {
                this.searchForm.page = 1
                this.handleFormData(val)
                this.$refs.tableList.getStockBalance(this.searchForm)
            },
            //处理非筛选方案表单项自定义和非自定义字段数据
            handleFormData(val){
                this.searchForm.searchOther = {}
                this.customFieldMap = {}
                for (const key in val) {
                    /**
                     * 自定义字段表单数据放在searchOther中的customFieldMap对象中
                     * 其中计数器--日期选择器--多选框以 `[自定义字段id]:'arr[0],arr[1]'` 形式传给后端
                     * 其它类型表单项以`[自定义字段id]:'value' 形式传给后端
                     */
                    if (!isNaN(parseFloat(key)) && isFinite(key)) { 
                        let str = ''
                        if(Array.isArray(val[key])){
                            val[key].forEach(k => str += k + ',')
                            if(str.length > 0) str = str.substr(0,str.length - 1)
                        }
                        this.customFieldMap[key] = Array.isArray(val[key]) ? str : val[key]
                        this.searchForm.searchOther.customFieldMap = this.customFieldMap
                    }else{ //非自定义字段表单数据放在searchOther对象中
                        this.searchForm.searchOther[key] = val[key]
                    }
                }
                //点击查询按钮时需要将筛选方案表单项数据和非筛选方案表单项数据同时接收，做合并查询
                if(this.editableTabs.length){ 
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.handleSchemeData(findTab)
                }
            },
            //关闭筛选方案列表
            fromOutDrawerClose(){
                if(this.editableTabs.length){ //当没有筛选方案时不需要调用列表接口
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.schemeClick(findTab)
                }
            },
            //删除筛选方案最后一条数据时
            lastData(){
                let payload = {
                    searchOther:{
                        typeOther:'-1'
                    },
                    page:1,
                    limit:10,
                }
                this.$refs.tableList.getStockBalance(payload)
            },
            //获取筛选方案列表
            getList(payload){
                this.fromSavaCurrent = payload == undefined || payload.length
                this.getScreenPlanList({type:2},payload == undefined || {delIndex:payload.delIndex,name:payload.name})
            },
            handleTabClick(tab){
                this.activeValue = 'all'
                const target = this.editableTabs.find(i => i.name == tab.label)
                this.schemeClick(target)
            },
            //获取二级分组信息
            getSecondGroupInfo(payload){
                const {typeCountData} = payload
                typeCountData.unshift({
                    optionName: "全部",
                    optionValue: "all"
                })
                this.secondGroupInfo = payload
            },
            //处理二级分组
            handleSecondGroup(group,secondGroupInfo){
                const {optionValue} = group
                const {key} = secondGroupInfo
                this.activeValue = optionValue
                this.searchForm.page = 1
                this.searchForm.secondSearchCondition = {
                    conditionName:optionValue === 'all' ? undefined : key,
                    conditionValue:optionValue === 'all' ? undefined : optionValue
                }
                this.$refs.tableList.getStockBalance(this.searchForm)
            },
            //筛选方案列表
            getScreenPlanList(data,p) {
                screenPlanList(data,p).then(res => {
                    if (res.code == 200) {
                        this.editableTabs = res.data.filter(i => i.isValid)
                        this.allTabs = res.data
                        if(!res.data.length) return //初始化进入页面时若无筛选方案不调用列表接口
                        /**
                         *  创建第一条筛选方案时tabs下划线默认选中，
                            当超过一条时，点击到第n个筛选方案，此时打开drawer再关闭tabs下划线默认为第n个
                         */
                        if(res.data.length && res.data.length == 1) this.editableTabsValue = res.data[0].name
                        /**
                         * 当选中第n个tabs标签页，此时打开筛选方案删除当前第n条数据时，tabs下划线默认向前移动一位
                         */
                        if(p != undefined && p.delIndex && p.name == this.editableTabsValue) {
                            this.editableTabsValue = res.data[p.delIndex - 1].name
                        }
                        /**
                         * 保存当前 || 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         * isMounted : 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         *             当创建第二条以上时将isMounted = '' 不需要再调用列表接口
                         */
                        if(this.fromSavaCurrent === 1 || this.isMounted == 'mounted') this.schemeClick(res.data[0])
                    }
                })
            },
            //tabs标签页--popover框
            schemeClick(item){
                this.searchForm = { //多个筛选方案互相切换先置空
                    customFieldMap:{},
                    searchOther:{},
                    screenPlanId:item.id,
                    page:1,
                    limit:10,
                }
                this.isMounted = ''
                /**
                 * getValue 这个方法单独获取已填写的非筛选方案表单项的数据
                 * 若通过selectData获取会触发'getFormData'导致每次点击筛选方案tabs标签重复调用列表接口
                 */
                let formDataPayload = this.$refs.dynamicForm.getValue()
                this.handleSchemeData(item)
                this.handleFormData(formDataPayload)
                this.$refs.tableList.getStockBalance(this.searchForm)
            },
             //处理筛选方案表单项自定义和非自定义字段数据
            handleSchemeData(item){
                let screenCondition = []
                let payload = {}
                screenCondition = JSON.parse(item.screenCondition).configData
                screenCondition.forEach(i => {
                    if(i.fieldId.indexOf('mum') != -1 || i.fieldId == 'safe' || i.fieldId == 'num'){
                        payload[i.fieldId + 'Down'] = i.fieldValue[0]
                        payload[i.fieldId + 'Up'] = i.fieldValue[1]
                    }else if(i.type != undefined && i.type != 'selectRadio' && i.type != 'ipt'){
                        let str = ''
                        i.fieldValue.forEach(k =>{
                            str += k + ','
                        })
                        if(str.length > 0) str = str.substr(0,str.length - 1)
                        payload[i.fieldId] = str
                    }else{
                        payload[i.fieldId] = i.fieldValue
                    }
                })
                this.editableTabsValue = item.name
                for (const key in payload) {
                    if (!isNaN(parseFloat(key)) && isFinite(key)) {
                        this.searchForm.customFieldMap[key] = payload[key]
                    }else{
                        this.searchForm[key] = payload[key]
                    }
                }
            },
            //库存余额导出
            getWorkOrderExport() {
                this.$refs.tableList.getTableData(
                    this.searchForm,
                    '/stock/stock_balance',
                    '库存余额' + new Date().dateFormat('yyyyMMddhhmmss'),
                    1
                )
            },
        }
    }
</script>

<style lang="less" scoped>
    .balanceReport {
        overflow: auto;

        .tabHeader {
            height: 44px;
            background-color: rgb(250, 250, 250);
            padding-left: 10px;

            .el-tabs {
                float: left;
                max-width: 1000px;
            }

            /deep/ .el-tabs__header {
                margin: 0;
                padding-top: 4px;
            }

            /deep/ .el-tabs__nav-wrap::after {
                opacity: 0;
            }

            /deep/ .el-tabs__item {
                padding: 0 10px;
            }

            /deep/ .el-tabs__item:first-child {
                padding-left: 0px;
            }
            /deep/ .el-tabs__item:last-child {
                padding-right: 0px;
            }


            /deep/ .el-tabs__nav {
                height: 40px;
            }

            /deep/ .el-tabs__nav-next, /deep/ .el-tabs__nav-prev{
                line-height: 38px;
            }

            .setBtn {
                float: right;
                margin-top: 8px;
                margin-right: 20px;
            }
        }

        .formSearch {
            position: relative;
            padding: 20px 20px 0;

            .searchContent {
                border-bottom: 1px solid #e8e8e8;
                display: flex;

                .btn {
                    button:nth-child(1) {
                        margin-right: 10px;
                    }

                    button:last-child {
                        height: 28px;
                        line-height: 7px
                    }
                }
            }

            .arrow {
                position: absolute;
                left: 50%;
                bottom: -14px;
                transform: translate(-50%, -50%);
                width: 40px;
                border: 1px solid #e8e8e8;
                border-radius: 18px;
                height: 14px;
                background: #fff;
                cursor: pointer;
                text-align: center;
                line-height: 11px;
                font-size: 12px;
            }

            .isShowMore {
                height: 47px;
                overflow: hidden;
            }
        }

        /deep/ .el-table__empty-block {
            width: 100% !important;
        }


        /deep/ th.el-table__cell.gutter {
            background-color: #fafafa;
        }

        /deep/ .el-dialog__body {
            padding: 10px 30px 10px 30px;

            .dialogBody {
                padding: 30px 50px 0;
                border: 1px solid #edeef3;
                background: #fbfbfb;

                .name,
                .el-checkbox-group {
                    float: left;
                }

                .name {
                    margin-right: 30px;
                }

                .el-checkbox-group {
                    width: 338px;

                    label.el-checkbox {
                        width: 130px;
                        margin-bottom: 10px;
                    }
                }
            }
        }
    }
</style>